#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 客户端发送给服务端字符串，服务端把字符串原封不动发回来
// 
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cout << "Wrong use\n";
        std::cout << "Usage: ./udp_client ip port\n";
        exit(-2);
    }

    // std::string server_ip = "127.0.0.1"; // 本地环回测试
    // std::string server_ip = "39.108.170.136";
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    // 创建套接字文件描述符
    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock_fd < 0)
    {
        std::cerr << "Create socket failed.\n";
        exit(-1);
    }

    // 给谁发？ --- 给server发消息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while(true)
    {
        std::string msg;
        std::cout << "[Say something]# ";
        std::getline(std::cin, msg);

        // 发送
        sendto(sock_fd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));

        // 接收
        struct sockaddr_in tmp;
        socklen_t tmp_len = sizeof(tmp);
        char buf[1024];
        int n = recvfrom(sock_fd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&tmp, &tmp_len);
        if(n > 0)
        {
            buf[n] = '\0';
            std::cout << "[Server echo]# " << buf << std::endl;
        }
    }

    return 0;
}